package com.label.Service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.label.Dao.EntityMapper;
import com.label.Dao.TagInfoMapper;
import com.label.Model.Do.Entity;
import com.label.Model.Query.*;
import com.label.Model.Vo.*;
import com.label.Service.EntityService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EntityServiceImpl extends ServiceImpl<EntityMapper, Entity> implements EntityService {

    @Resource
    private EntityMapper entityMapper;

    @Resource
    private TagInfoMapper tagInfoMapper;

    @Resource
    @Qualifier("sparkSqlJdbcTemplate")
    private JdbcTemplate sparkJdbc;

    @Resource
    @Qualifier("oracleJdbcTemplate")
    private JdbcTemplate oracleJdbc;

    @Override
    public Boolean entityAddTag(EntityQuery entityQuery) {
        Entity entity= BeanUtil.copyProperties(entityQuery,Entity.class);
        List<Entity> entities=entityMapper.selectList(new QueryWrapper<Entity>().lambda().eq(Entity::getEntityType,entityQuery.getEntityType()).eq(Entity::getEntityId,entityQuery.getEntityId()).eq(Entity::getTagId,entity.getTagId()));
        if(entities.size()!=0)
            return false;
        return entityMapper.insert(entity) == 1;

        //todo:取数据
      //  sparkJdbc.queryForList(select * from personportraitdatapar where portraitid="+id+" and theme='studentprofile')
    }

    @Override
    public Boolean entityDelTag(EntityQuery entityQuery) {
        return entityMapper.delete(new QueryWrapper<Entity>().lambda().eq(Entity::getEntityType,entityQuery.getEntityType()).eq(Entity::getEntityId,entityQuery.getEntityId()).eq(Entity::getTagId,entityQuery.getTagId()))!=0;
    }

    @Override
    public List<ActivityTagVo> getAllCourseInfo() {
        return entityMapper.getAllCourseInfo();
    }

    @Override
    public List<ActivityTagVo> getOneCourseInfo(ActivityTagVo courseTagVo) {
        return entityMapper.getOneCourseInfo(courseTagVo.getActivityName(),courseTagVo.getStartTime(),courseTagVo.getEndTime()  );
    }

    @Override
    public List<StuTagVo> getAllStuInfo() {
        return entityMapper.getAllStuInfo();
    }

    @Override
    public List<StuTagVo> getOneStuInfo(StuTagVoQuery stuTagVoQuery) {
        List<String> userIds=null;
        if(stuTagVoQuery.getPersons()!=null&&!"".equals(stuTagVoQuery.getPersons())){
//            userIds=sparkJdbc.queryForList("select entityid from hive.personportraitdatapar where portraitid='"+stuTagVoQuery.getPersons()+"'").stream().map(p->p.get("ENTITYID").toString()).collect(Collectors.toList());
            userIds=oracleJdbc.queryForList("select entityid from personportraitdatapar where portraitid='"+stuTagVoQuery.getPersons()+"'").stream().map(p->p.get("ENTITYID").toString()).collect(Collectors.toList());
        }
        return entityMapper.getOneStuInfo(stuTagVoQuery.getUserId(),stuTagVoQuery.getClassPosition(),stuTagVoQuery.getUnionPosition(),userIds, stuTagVoQuery.getClassId() ,stuTagVoQuery.getPolitics());
    }

    @Override
    public List<DorTagVo> getAllDorInfo() {
        return entityMapper.getAllDorInfo();
    }

    @Override
    public List<DorTagVo> getOneDorInfo(DorTagQuery dorTagQuery) {
        List<String> dors=null;
        if(dorTagQuery.getPersons()!=null&&!"".equals(dorTagQuery.getPersons())){
//            dors=sparkJdbc.queryForList("select entityid from hive.personportraitdatapar where portraitid='"+dorTagQuery.getPersons()+"'").stream().map(p->p.get("ENTITYID").toString()).collect(Collectors.toList());
            dors=oracleJdbc.queryForList("select entityid from personportraitdatapar where portraitid='"+dorTagQuery.getPersons()+"'").stream().map(p->p.get("ENTITYID").toString()).collect(Collectors.toList());
        }
        return entityMapper.getOneDorInfo(dorTagQuery.getEnrollyear(),dorTagQuery.getClassId(), dorTagQuery.getDormitory(), dors);
    }

    @Override
    public List<ClassTagVo> getAllClassInfo() {
        return entityMapper.getAllClassInfo();
    }

    @Override
    public List<ClassTagVo> getOneClassInfo(ClassTagQuery classTagQuery) {
        List<String> classes=null;
        if(classTagQuery.getPersons()!=null&&!"".equals(classTagQuery.getPersons())){
//            classes=sparkJdbc.queryForList("select entityid from hive.personportraitdatapar where portraitid='"+classTagQuery.getPersons()+"'").stream().map(p->p.get("ENTITYID").toString()).collect(Collectors.toList());
            classes=oracleJdbc.queryForList("select entityid from personportraitdatapar where portraitid='"+classTagQuery.getPersons()+"'").stream().map(p->p.get("ENTITYID").toString()).collect(Collectors.toList());
        }
        return entityMapper.getOneClassInfo(classTagQuery.getEnrollyear(),classTagQuery.getClassId(),classes);
    }

    @Override
    public List<ResultVo> getPoint(TagInfoQuery tagInfoQuery) {
        List<Entity> entities=entityMapper.selectList(new QueryWrapper<Entity>().lambda().eq(Entity::getTagId,tagInfoQuery.getTagId()).eq(Entity::getEntityType,tagInfoQuery.getType()));
        List<String> userIds=new ArrayList<>();

        String ids = entities.stream().map(Entity::getEntityId).collect(Collectors.toList()).stream().map(s -> "\'" + s + "\'").collect(Collectors.joining(","));
        if("".equals(ids))
            return null;

        switch (tagInfoQuery.getType()){
            case "1"://二课
                userIds=oracleJdbc.queryForList("select user_id from activity_attend where ACTIVITY_ID in ("+ids+")").stream().map(p->p.get("USER_ID").toString()).collect(Collectors.toList());break;
            case "2"://学生
                userIds=entities.stream().map(Entity::getEntityId).collect(Collectors.toList());break;
            case "3"://宿舍
                userIds=oracleJdbc.queryForList("select userid from STUDENTATTR where DORMITORY in ("+ids+")").stream().map(p->p.get("USER_ID").toString()).collect(Collectors.toList());break;
            case "4"://班级
                userIds=oracleJdbc.queryForList("select user_id from STUDENTATTR where CLASSID in ("+ids+")").stream().map(p->p.get("USER_ID").toString()).collect(Collectors.toList());break;
        }

        if(userIds.size()==0)
            return null;
        userIds=userIds.stream().distinct().collect(Collectors.toList());

        List<ResultVo> resultVos=null;

        String inStr=GetWhereInValuesSql("USERID",userIds,1000);
        switch (tagInfoQuery.getType()){
            case "1"://二课
                resultVos=entityMapper.getCoursePoint(inStr);break;
            case "2"://学生
                resultVos=entityMapper.getStuPoint(inStr);break;
            case "3"://宿舍
                resultVos=entityMapper.getDorPoint(inStr);break;
            case "4"://班级
                resultVos=entityMapper.getClassPoint(inStr);break;
        }
        if(resultVos==null)
            return null;
        return resultVos.stream().sorted((o1, o2) -> {
            if(o1.getPoint()==null||o2.getPoint()==null)
                if(o1.getPoint()==null)
                    return 1;
                else
                    return -1;
            else
                return (int) (o2.getPoint()-o1.getPoint());
        }).collect(Collectors.toList());
    }


    String GetWhereInValuesSql(String column, List<String> values,int num) {
        // sql语句
        String sql = "(";
        // 值的个数
        int valueSize = values.size();
        // 批次数
        int batchSize = valueSize / num + (valueSize % num == 0 ? 0 : 1);
        for (int i = 0; i < batchSize; i++) {
            if (i > 0) {
                sql += ") or ";
            }
            sql += column+" in (";
            for (int j = i * num; ( j < (i + 1) * num) && j < valueSize; j++) {
                if (j > i * num) {
                    sql += ",";
                }
                sql += "'" + values.get(j) + "'";
            }
        }
        sql += "))";
        return sql;
    }
}
